import requests
import re
import json
import csv
from datetime import datetime
from time import sleep


def fetch_dlt_data():
    base_url = "https://jc.zhcw.com/port/client_json.php"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
        "Referer": "https://www.zhcw.com/"
    }

    all_data = []  # 抓取结果
    target_count = 100  #目标数据量
    current_page = 1    #当前页码
    max_pages = 6  # 最多尝试6页

    while len(all_data) < target_count and current_page <= max_pages:
        params = {
            "callback": "jQuery112209275010394041369_1751955569974",
            "transactionType": "10001001",
            "lotteryId": "281",
            "issueCount": "150",
            "pageNum": str(current_page),
            "pageSize": "30",
            "tt": "0.9597601592849322",
            "_": "1751955569979",
            "type": "0"
        }

        try:
            response = requests.get(base_url, params=params, headers=headers, timeout=10)

            # 处理JSONP响应
            json_str = re.sub(r'^jQuery\d+_\d+\(|\)$', '', response.text)
            page_data = json.loads(json_str)

            # 筛选7月1日前的数据
            for item in page_data["data"]:
                open_date = datetime.strptime(item["openTime"], "%Y-%m-%d")
                if open_date >= datetime(2025, 7, 1):
                    continue

                simplified_data = {
                    "期号": item["issue"],
                    "开奖日期": item["openTime"],
                    "前区号码": item["frontWinningNum"],
                    "后区号码": item["backWinningNum"],
                    "销售额": item["saleMoney"],
                    "奖池金额": item["prizePoolMoney"],
                    "星期": item["week"]
                }
                all_data.append(simplified_data)

                if len(all_data) >= target_count:
                    break

            print(f"已成功获取第{current_page}页数据，当前总计{len(all_data)}条记录")
            current_page += 1
            sleep(0.5)

        except Exception as e:
            print(f"第{current_page}页数据获取失败: {e}")
            break

    return all_data[:target_count]  # 确保返回100条


def save_to_csv(data, filename="data_100.csv"):
    with open(filename, 'w', newline='', encoding='utf-8-sig') as csvfile:
        fieldnames = ["期号", "开奖日期", "前区号码", "后区号码", "销售额", "奖池金额", "星期"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(data)
    print(f"数据已保存至{filename}，共{len(data)}条记录")


if __name__ == "__main__":
    dlt_data = fetch_dlt_data()
    save_to_csv(dlt_data)